package com.spzx.payment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.domain.R;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.order.api.RemoteOrderInfoService;
import com.spzx.order.domain.OrderInfo;
import com.spzx.order.domain.OrderItem;
import com.spzx.payment.domain.PaymentInfo;
import com.spzx.payment.mapper.PaymentInfoMapper;
import com.spzx.payment.service.IPaymentInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 付款信息表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2025-02-28
 */
@Service
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements IPaymentInfoService {


    @Autowired
    private RemoteOrderInfoService remoteOrderInfoService;

    @Autowired
    private RabbitService rabbitService;

    /**
     * 保存本地交易记录
     *
     * @param orderNo
     * @return
     */
    @Override
    public PaymentInfo savePaymentInfo(String orderNo) {
        //1.根据订单编号查询本地交易记录，如果存在返回即可
        LambdaQueryWrapper<PaymentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentInfo::getOrderNo, orderNo);
        PaymentInfo paymentInfo = baseMapper.selectOne(queryWrapper);
        if (paymentInfo != null) {
            return paymentInfo;
        }
        //2.封装交易记录对象，保存到数据库中
        paymentInfo = new PaymentInfo();

        R<OrderInfo> r = remoteOrderInfoService.getByOrderNo(orderNo, SecurityConstants.INNER);
        if (R.FAIL == r.getCode()) {
            throw new RuntimeException("远程调用获取订单信息失败");
        }
        OrderInfo orderInfo = r.getData();
        paymentInfo.setUserId(orderInfo.getUserId());
        paymentInfo.setOrderNo(orderNo);
        paymentInfo.setPayType(2);
        paymentInfo.setAmount(orderInfo.getTotalAmount());
        List<OrderItem> orderItemList = orderInfo.getOrderItemList();
        if (!CollectionUtils.isEmpty(orderItemList)) {
            String content = orderItemList.stream().map(OrderItem::getSkuName)
                    .collect(Collectors.joining(","));
            paymentInfo.setContent(content);
        }
        paymentInfo.setPaymentStatus(0);
        paymentInfo.setCreateBy(orderInfo.getNickName());
        //TODO 以下三个字段：支付宝端交易号；支付宝端交易时间；支付宝端交易内容等用户付款后，系统收到支付宝回调后才能更新
        //paymentInfo.setTradeNo();
        //paymentInfo.setCallbackTime();
        //paymentInfo.setCallbackContent();
        baseMapper.insert(paymentInfo);
        return paymentInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePaymentInfo(PaymentInfo paymentInfo, Map<String, String> paramsMap) {
        //1.修改本地交易记录状态包括回调时间，回调内容
        if (paymentInfo.getPaymentStatus() == 1) {
            return;
        }
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(paramsMap.toString());
        String tradeNo = paramsMap.get("trade_no");
        paymentInfo.setTradeNo(tradeNo);
        paymentInfo.setPaymentStatus(1);
        baseMapper.updateById(paymentInfo);
        //2.采用MQ异步通知订单服务修改订单状态：已支付
        rabbitService.sendMessage(MqConst.EXCHANGE_PAYMENT_PAY, MqConst.ROUTING_PAYMENT_PAY, paymentInfo.getOrderNo());

        //3.采用MQ异步通知商品服务库存扣减
        rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.ROUTING_MINUS, paymentInfo.getOrderNo());

    }
}
